/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.service.fm.reactor;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import fr.jade.base.JadeBaseComponent;
import fr.jade.fraclite.api.control.NoSuchAttributeException;
import fr.jade.service.fm.deployment.DeploymentTask;

public class BasicPlanner extends JadeBaseComponent implements Planner {
  
  protected static final String workflowAttName = "workflow";
  protected String workflow = null;
  protected String separ = ":";
  
  protected static final String[] listAtt = new String[] {workflowAttName};

  public List<DeploymentTask> createPlan(Set<DeploymentTask> recoveryTasks) {
    assert workflow != null : "workflow attribute can't be null";
    
    String[] steps = workflow.split(separ);
    Map<String, List<DeploymentTask>> recoveryMap = new HashMap<String, List<DeploymentTask>>(steps.length);
    for(String step : steps){
      recoveryMap.put(step, new LinkedList<DeploymentTask>());
    }
    
    for(DeploymentTask dt : recoveryTasks){
      recoveryMap.get(dt.getLevelName()).add(dt);
    }
    
    List<DeploymentTask> recoveryPlan = new LinkedList<DeploymentTask>();
    for(String step : steps){
      log(step+": "+recoveryMap.get(step).size()+" tasks");
      recoveryPlan.addAll(recoveryMap.get(step));
    }
    return recoveryPlan;
  }

  @Override
  public String getAttribute(String name) throws NoSuchAttributeException {
    if(name.equals(workflowAttName)){
      return workflow;
    }else{
      return super.getAttribute(name);
    }
  }

  @Override
  public String[] listFcAtt() {
    return super.concat(listAtt, super.listFcAtt());
  }

  @Override
  public void setAttribute(String name, String value) throws NoSuchAttributeException {
    if(name.equals(workflowAttName)){
      workflow = value;
    }else{
      super.setAttribute(name, value);
    }
  }
  
}
